////////////////////////////////////////////////////////////////////////////////////////
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING THIS SOFTWARE
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install, copy or use the software.
//
// Copyright (C) 2013, AerVision Technologies Pty Ltd, all rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of AerVision Technologies, may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors to demonstrate 
// www.AerCloud.net Framework as a Service API (FaaS), "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the copyright holder or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
////////////////////////////////////////////////////////////////////////////////////////

package com.aercloud.client.gui;

import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.AbstractAction;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.border.Border;

import org.apache.log4j.Logger;

import com.aercloud.client.util.AerCloudClient;

public class PanelMain extends JPanel {
    
    private class ActionConnect extends AbstractAction {

        public ActionConnect(String arg0) {
            super(arg0);
        }

        @Override
        public void actionPerformed(ActionEvent arg0) {
            PanelMain.this.connect();
        }

    }
    
    private class ActionSaveFace extends AbstractAction {
        
        public ActionSaveFace(String name) {
            super(name);
            setEnabled(false);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            PanelMain.this.getPanelStep2().saveFace(
                PanelMain.this.getAerCloudClient(), 
                PanelMain.this.getPanelStep1().getPanelStep1Controls().getAccessKey());
        }
    }
    
    private class ActionBrowseDatabase extends AbstractAction {
        
        public ActionBrowseDatabase(String name) {
            super(name);
        }
        
        @Override
        public void actionPerformed(ActionEvent e) {
            PanelMain.this.getPanelStep3().getFrameDatabaseBrowser().setVisible(true);
            PanelMain.this.getPanelStep3().getFrameDatabaseBrowser().getPanelDatabaseBrowserContentPane().getPanelDatabaseBrowser().query(
                PanelMain.this.getAerCloudClient(), 
                PanelMain.this.getPanelStep1().getPanelStep1Controls().getAccessKey());
        }
    }
    
    private class ActionDeleteName extends AbstractAction {
        
        public ActionDeleteName(String name) {
            super(name);
        }
        @Override
        public void actionPerformed(ActionEvent paramActionEvent) {
            PanelDatabaseBrowserItem panelDatabaseBrowserItem =
                (PanelDatabaseBrowserItem)PanelMain.this.imagePopupMenuTrigger.getComponent();
            PanelMain.this.getPanelStep3().getFrameDatabaseBrowser().getPanelDatabaseBrowserContentPane().getPanelDatabaseBrowser().delete(
                PanelMain.this.getAerCloudClient(), 
                PanelMain.this.getPanelStep1().getPanelStep1Controls().getAccessKey(),
                panelDatabaseBrowserItem);
        }
    }
    
    private class ActionSearchFace extends AbstractAction {
        
        public ActionSearchFace(String name) {
            super(name);
            setEnabled(false);
       }
        
        @Override
        public void actionPerformed(ActionEvent paramActionEvent) {
            PanelMain.this.getPanelStep4().search(
                PanelMain.this.getAerCloudClient(), 
                PanelMain.this.getPanelStep1().getPanelStep1Controls().getAccessKey());
        }
    }
    
    private class ActionDeleteImage extends AbstractAction {
        
        public ActionDeleteImage(String name) {
            super(name);
        }
        @Override
        public void actionPerformed(ActionEvent paramActionEvent) {
            PanelDatabaseBrowserItemImages panelDatabaseBrowserItemImages =
                (PanelDatabaseBrowserItemImages)PanelMain.this.imagePopupMenuTrigger.getComponent();
            panelDatabaseBrowserItemImages.delete(
                PanelMain.this.getAerCloudClient(), 
                PanelMain.this.getPanelStep1().getPanelStep1Controls().getAccessKey(),
                panelDatabaseBrowserItemImages.getComponentAt(
                    PanelMain.this.imagePopupMenuTrigger.getX(),
                    PanelMain.this.imagePopupMenuTrigger.getY()));
        }
    }
    
    private class ShadowBorder implements Border
    {
        public void paintBorder( Component c, Graphics g, int x, int y, int width, int height )
        {
          g.setColor( Color.GRAY ) ;
          g.fillRect( x + width - 4, y + 4, 4, height - 4 ) ;
          g.fillRect( x + 4, y + height - 4, width - 4, 4 ) ;
        }
     
        public Insets getBorderInsets( Component c )
        {
          return new Insets( 3, 3, 6, 6 ) ;
        }
     
        public boolean isBorderOpaque()
        {
          return true ;
        }
    }
    
    private static Logger log = Logger.getLogger(PanelMain.class);
    
    private AerCloudClient aerCloudClient;
    private JPopupMenu imagePopupMenu;
    private MouseEvent imagePopupMenuTrigger;
    
    private TabbedPaneSteps tabbedPaneSteps;
    private AutoScrollTextArea autoScrollTextArea;
    private PanelStep1 panelStep1;
    private PanelStep2 panelStep2;
    private PanelStep3 panelStep3;
    private PanelStep4 panelStep4;

    /**
     * Create the panel.
     */
    public PanelMain() {
        GridBagLayout gridBagLayout = new GridBagLayout();
        gridBagLayout.columnWidths = new int[]{0};
        gridBagLayout.rowHeights = new int[]{0, 0};
        gridBagLayout.columnWeights = new double[]{1.0};
        gridBagLayout.rowWeights = new double[]{1.0, 1.0};
        setLayout(gridBagLayout);
        
        GridBagConstraints gbc_tabbedPaneSteps = new GridBagConstraints();
        gbc_tabbedPaneSteps.fill = GridBagConstraints.BOTH;
        gbc_tabbedPaneSteps.gridx = 0;
        gbc_tabbedPaneSteps.gridy = 0;
        add(getTabbedPaneSteps(), gbc_tabbedPaneSteps);
        
        GridBagConstraints gbc_autoScrollTextArea = new GridBagConstraints();
        gbc_autoScrollTextArea.fill = GridBagConstraints.BOTH;
        gbc_autoScrollTextArea.gridx = 0;
        gbc_autoScrollTextArea.gridy = 1;
        add(getAutoScrollTextArea(), gbc_autoScrollTextArea);
    }
    
    public PanelMain(JFrame frame) {
        this();
        getPanelStep2().setFrame(frame);
        getPanelStep4().setFrame(frame);
    }
    
    public void connect() {
        new Thread(new Runnable(){
            @Override
            public void run() {
                getPanelStep1().getPanelStep1Controls().connect(getAerCloudClient());
            }
        }).start();
    }
    
    public AerCloudClient getAerCloudClient() {
        if(aerCloudClient == null) {
            aerCloudClient = new AerCloudClient(); 
        }
        return aerCloudClient;
    }

    public JPopupMenu getImagePopupMenu() {
        if(imagePopupMenu == null) {
            imagePopupMenu = new JPopupMenu();
            imagePopupMenu.setBorder(new ShadowBorder());
            imagePopupMenu.add(new JMenuItem(new ActionDeleteName("Delete"))); 
//            imagePopupMenu.add(new JMenuItem(new ActionDeleteImage("Delete"))); 
        }
        return imagePopupMenu;
    }

    public TabbedPaneSteps getTabbedPaneSteps() {
        if (tabbedPaneSteps == null) {
        	tabbedPaneSteps = new TabbedPaneSteps();
        	tabbedPaneSteps.addTab("Step 1. Access Key", null, getPanelStep1(), null);
        	tabbedPaneSteps.addTab("Step 2. Save Face", null, getPanelStep2(), null);
        	tabbedPaneSteps.addTab("Step 3. Browse Database", null, getPanelStep3(), null);
        	tabbedPaneSteps.addTab("Step 4. Search Face", null, getPanelStep4(), null);
        }
        return tabbedPaneSteps;
    }
    
    public AutoScrollTextArea getAutoScrollTextArea() {
        if (autoScrollTextArea == null) {
        	autoScrollTextArea = FrameMain.CONSOLE;
        }
        return autoScrollTextArea;
    }
    
    public PanelStep1 getPanelStep1() {
        if (panelStep1 == null) {
        	panelStep1 = new PanelStep1();
        	panelStep1.getPanelStep1Controls().getBtnConnect().setAction(new ActionConnect("Connect"));
        }
        return panelStep1;
    }
    
    public PanelStep2 getPanelStep2() {
        if (panelStep2 == null) {
        	panelStep2 = new PanelStep2();
        	panelStep2.getPanelList().getBtnSave().setAction(new ActionSaveFace("Click to save"));
        }
        return panelStep2;
    }
    
    public PanelStep3 getPanelStep3() {
        if (panelStep3 == null) {
        	panelStep3 = new PanelStep3();
        	panelStep3.getBtnBrowseDatabase().setAction(new ActionBrowseDatabase("Browse Database ..."));
        	panelStep3.getFrameDatabaseBrowser().getPanelDatabaseBrowserContentPane().getPanelDatabaseBrowser()
        	    .setImagePopupMouseListener(new MouseAdapter() {
                    @Override
                    public void mouseReleased(MouseEvent e) {
                        maybeShowPopup(e);
                    }
                    private void maybeShowPopup(MouseEvent e) {
                        if (e.getModifiers() == e.META_MASK) { // isPopupTrigger() doesn't work under linux
                            PanelMain.this.imagePopupMenuTrigger = e;
                            PanelMain.this.getImagePopupMenu()
                                .show(e.getComponent(), e.getX(), e.getY());
                        }
                    }
    	    });
        }
        return panelStep3;
    }
    
    public PanelStep4 getPanelStep4() {
        if (panelStep4 == null) {
        	panelStep4 = new PanelStep4();
        	panelStep4.getPanelList().getBtnSearch().setAction(new ActionSearchFace("Click to initiate face search ..."));
        }
        return panelStep4;
    }
}
